import iconFont from '@/assets/iconFont/iconfont.less';
import { BatteryInfoProps } from '@/pages/OverView/components/BatteryInfo';
import { DischargeDataInfo } from '@/pages/OverView/components/DischargeInfo';
import { IEvent } from '@/pages/OverView/components/EventInfo';
import { OperatingStatus } from '@/pages/OverView/components/OperatingInfo';
import { PowerStatus } from '@/pages/OverView/components/PowerView';
import { photovolaticStatusesType } from '@/pages/OverView/photovoltaic/type';

import {
  mainPageControllerGetChargeAndDischarge,
  mainPageControllerGetEventDatas,
  mainPageControllerGetOverviewData,
  mainPageControllerGetStatisticsData,
  mainPageControllerGetWorkState,
} from '@/services/ess/mainpageStation';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { formatterUnit } from '@/utils/formatterUnit';
import { useIntl } from '@umijs/max';
import cls from 'classnames';
import _, { isNull } from 'lodash';
import { useEffect, useState } from 'react';
import Styles from '../index.less';
import { formatPower } from './tools';

interface HomeDataProps {
  stationStatuses: OperatingStatus[];
  stationRealStatuses: PowerStatus[];
  stationBaseStatus: PowerStatus[];
  stationBatteryData: BatteryInfoProps[];
  stationMainData: API.MainRealtimeData | undefined;
  stationBaseData: API.StationBaseInfo;
  stationPolicyEvent: IEvent[];
  stationWarningEvent: IEvent[];
  stationWorkState: API.WorkstateVO | undefined;
  stationChargeAndDischarge: DischargeDataInfo;
  photovolaticStatuses: photovolaticStatusesType;
  stationRealtimeData: API.StationRealtimeData;
}

export const useFetchHomeData = (
  stationId?: string | number,
  isOldStation = false,
  areaId?: string | number,
  isPhotovoltaic = false,
) => {
  const [homeData, setHomeData] = useState<HomeDataProps>({
    stationStatuses: [],
    stationRealStatuses: [],
    stationBaseStatus: [],
    stationBatteryData: [],
    stationMainData: [] as API.MainRealtimeData,
    stationBaseData: [] as API.StationBaseInfo,
    stationRealtimeData: [] as API.StationRealtimeData,
    stationPolicyEvent: [],
    stationWarningEvent: [],
    stationWorkState: [] as API.WorkstateVO,
    stationChargeAndDischarge: {
      dimensions: [],
      source: [],
    },
    photovolaticStatuses: {
      storageCharge: {
        day: '-',
        month: '-',
        year: '-',
      },
      storageDischarge: {
        day: '-',
        month: '-',
        year: '-',
      },
      powerGeneration: {
        day: '-',
        month: '-',
        year: '-',
      },
      powerConsumption: {
        day: '-',
        month: '-',
        year: '-',
      },
      onGrid: {
        day: '-',
        month: '-',
        year: '-',
      },
      offGrid: {
        day: '-',
        month: '-',
        year: '-',
      },
      environmentalParameters: {
        tandardCoalConservation: '-',
        carbonDioxideEmissionReduction: '-', // 假设单位为 t，可以换成其他单位
      },
    },
  });

  const intl = useIntl();
  useEffect(() => {
    if (!stationId) return;

    const fetchStatisticsData = async () => {
      try {
        const statisticsResponse = await mainPageControllerGetStatisticsData({
          stationId: stationId,
          areaId: areaId,
        });

        if (statisticsResponse.success) {
          const data = statisticsResponse.data;
          const pocOffGridEnergyFormat = formatPower(Number(data?.pocOffGridEnergy || NaN));
          const pocOnGridEnergyFormat = formatPower(Number(data?.pocOnGridEnergy || NaN));
          const newStatuses = [
            {
              OperatingTitle: intl.formatMessage({ id: 'overviewPages.totalRevenues' }),
              OperatingCount: data?.historyIncome ? data?.historyIncome : '--',
            },
            {
              OperatingTitle: intl.formatMessage({ id: 'overviewPages.annualRevenues' }),
              OperatingCount: data?.yearIncome ? data?.yearIncome : '--',
            },
            {
              OperatingTitle: intl.formatMessage({ id: 'overviewPages.totalOnGridEnergy' }),
              OperatingCount: pocOnGridEnergyFormat ? pocOnGridEnergyFormat.value : '--',
              OperatingUnit: pocOnGridEnergyFormat.unit,
            },
            {
              OperatingTitle: intl.formatMessage({ id: 'overviewPages.totalOffGridEnergy' }),
              OperatingCount: pocOffGridEnergyFormat ? pocOffGridEnergyFormat.value : '--',
              OperatingUnit: pocOffGridEnergyFormat.unit,
            },
            {
              OperatingTitle: intl.formatMessage({ id: 'overviewPages.dayDepthDischarge' }),
              OperatingCount: data?.dischargeDoD ? parseFloat(data?.dischargeDoD).toFixed(2) : '--',
              OperatingUnit: '%',
            },
            {
              OperatingTitle: intl.formatMessage({
                id: 'overviewPages.annualEquivalentOperatingHours',
              }),
              OperatingCount: data?.yearRunHours ? parseFloat(data?.yearRunHours).toFixed(2) : '--',
            },
            {
              OperatingTitle: intl.formatMessage({ id: 'overviewPages.annualLossRate' }),
              OperatingCount: data?.yearLoss ? parseFloat(data?.yearLoss).toFixed(2) : '--',
              OperatingUnit: '%',
            },
            {
              OperatingTitle: intl.formatMessage({
                id: 'overviewPages.annualEquivalentUtilizationFactor',
              }),
              OperatingCount: data?.yearEquivalent
                ? parseFloat(data?.yearEquivalent).toFixed(2)
                : '--',
              OperatingUnit: '%',
            },
            {
              OperatingTitle: intl.formatMessage({
                id: 'overviewPages.annualChargeDiachargeRoundtripEfficiency',
              }),
              OperatingCount: data?.yearConversion
                ? parseFloat(data?.yearConversion).toFixed(2)
                : '--',
              OperatingUnit: '%',
            },
            {
              OperatingTitle: intl.formatMessage({
                id: 'overviewPages.annualEquivalentDischargeTimes',
              }),
              OperatingCount: data?.yearDischarge ? data?.yearDischarge : '--',
            },
          ];
          setHomeData((prev) => ({
            ...prev,
            stationStatuses: newStatuses,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };
    const fetchPhotovolaticStaticData = async () => {
      try {
        const statisticsResponse = await mainPageControllerGetStatisticsData({
          stationId: stationId,
          areaId: areaId,
        });
        if (statisticsResponse.success) {
          const data = statisticsResponse.data;

          const statisticData = {
            storageCharge: {
              day: formatterUnit(data?.dayStats?.chargedEnergy),
              month: formatterUnit(data?.monthStats?.chargedEnergy),
              year: formatterUnit(data?.yearStats?.chargedEnergy),
            },
            storageDischarge: {
              day: formatterUnit(data?.dayStats?.dischargedEnergy),
              month: formatterUnit(data?.monthStats?.dischargedEnergy),
              year: formatterUnit(data?.yearStats?.dischargedEnergy),
            },
            powerGeneration: {
              day: formatterUnit(data?.dayStats?.generatedEnergy),
              month: formatterUnit(data?.monthStats?.generatedEnergy),
              year: formatterUnit(data?.yearStats?.generatedEnergy),
            },
            powerConsumption: {
              day: formatterUnit(data?.dayStats?.usedEnergy),
              month: formatterUnit(data?.monthStats?.usedEnergy),
              year: formatterUnit(data?.yearStats?.usedEnergy),
            },
            onGrid: {
              day: formatterUnit(data?.dayStats?.onlineEnergy),
              month: formatterUnit(data?.monthStats?.onlineEnergy),
              year: formatterUnit(data?.yearStats?.onlineEnergy),
            },
            offGrid: {
              day: formatterUnit(data?.dayStats?.offlineEnergy),
              month: formatterUnit(data?.monthStats?.offlineEnergy),
              year: formatterUnit(data?.yearStats?.offlineEnergy),
            },
            environmentalParameters: {
              tandardCoalConservation: isNull(data?.conservedCoal)
                ? '-'
                : data?.conservedCoal + 't',
              carbonDioxideEmissionReduction: isNull(data?.reducedCO2)
                ? '-'
                : data?.reducedCO2 + 't', // 假设单位为 t，可以换成其他单位
            },
          };
          setHomeData((prev) => ({
            ...prev,
            photovolaticStatuses: statisticData,
          }));
        }
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    };
    const fetchOverviewData = async () => {
      try {
        const response = await mainPageControllerGetOverviewData({
          stationId: stationId,
          areaId: areaId,
        });
        const stationRunStatus = await fetchDictInfo(DATABASE_TYPE_ENUM.OVERVIEW_RUN_STATUS);
        const stationStatus =
          stationRunStatus.find(
            (item) => item.value === String(response.data?.realtimeData?.runStatus),
          )?.label || '--';
        const stationChargeStatus =
          stationRunStatus.find(
            (item) => item.value === String(response.data?.realtimeData?.workState),
          )?.label || '--';

        if (response.success) {
          const data = response.data;
          const chargableEnergyFormat = formatPower(data?.realtimeData?.chargableEnergy);
          const dischargableEnergyFormat = formatPower(data?.realtimeData?.dischargableEnergy);
          const todayChargedEnergyFormat = formatPower(data?.realtimeData?.todayChargedEnergy);
          const todayDischargedEnergyFormat = formatPower(
            data?.realtimeData?.todayDischargedEnergy,
          );
          const stationRealStatuses = [
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe876;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.plantOperation' }),
              value: stationStatus,
              unit: '',
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe871;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.chargeOperation' }),
              value: stationChargeStatus,
              unit: '',
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe87c;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.chargeable' }),
              value: chargableEnergyFormat ? chargableEnergyFormat.value : '--',
              unit: chargableEnergyFormat.unit,
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe874;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.dischargeable' }),
              value: dischargableEnergyFormat ? dischargableEnergyFormat.value : '--',
              unit: dischargableEnergyFormat.unit,
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe873;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.dayCharge' }),
              value: todayChargedEnergyFormat ? todayChargedEnergyFormat.value : '--',
              unit: todayChargedEnergyFormat.unit,
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe878;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.dayDischarge' }),
              value: todayDischargedEnergyFormat ? todayDischargedEnergyFormat.value : '--',
              unit: todayDischargedEnergyFormat.unit,
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe877;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.chargeTimes' }),
              value: data?.realtimeData?.todayChargedCount
                ? data?.realtimeData?.todayChargedCount
                : 0,
              unit: intl.formatMessage({ id: 'global.times' }),
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe875;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.dischargeTimes' }),
              value: data?.realtimeData?.todayDischargedCount
                ? data?.realtimeData?.todayDischargedCount
                : 0,
              unit: intl.formatMessage({ id: 'global.times' }),
            },
          ];
          setHomeData((prev) => ({
            ...prev,
            stationRealStatuses: stationRealStatuses,
          }));
        }
      } catch (error) {
        console.error('Failed to load overview data:', error);
      }
    };

    const fetchBaseOverview = async () => {
      try {
        // 获取站点类型字典信息
        const stationTypeDict = await fetchDictInfo(DATABASE_TYPE_ENUM.SITE_TYPE);
        const response = await mainPageControllerGetOverviewData({
          stationId: stationId,
          areaId: areaId,
        });
        if (response.success) {
          const data = response.data;
          const capacityFormat = formatPower(data?.baseData?.capacity);
          const ratedPowerFormat = formatPower(data?.baseData?.ratedPower, true);
          const stationTypeName =
            stationTypeDict.find((item) => item.value === data?.baseData?.stationType)?.label ||
            '--';

          const address = data?.baseData?.address || '';
          const isLongAddress = address.length > 25;

          const stationBaseStatus = [
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe876;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.plantType' }),
              value: stationTypeName,
              unit: '',
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe87d;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.operationTime' }),
              value: data?.baseData?.startRunTime ? data?.baseData?.startRunTime : '--',
              unit: '',
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe870;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.ratedCapacity' }),
              value: capacityFormat.value ? capacityFormat.value : '--',
              unit: capacityFormat.unit,
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe872;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.ratedPower' }),
              value: ratedPowerFormat.value ? ratedPowerFormat.value : '--',
              unit: ratedPowerFormat.unit,
            },
            {
              icon: (
                <span
                  style={{
                    color: '#1677ff',
                    fontSize: '18px',
                    lineHeight: '18px',
                    fontWeight: 400,
                  }}
                  className={cls([iconFont.iconfont])}
                >
                  &#xe879;
                </span>
              ),
              title: intl.formatMessage({ id: 'overviewPages.plantLocation' }),
              value: isLongAddress ? (
                <span className={Styles.addressEllis}>{address}</span>
              ) : (
                address
              ),
              unit: '',
            },
          ];

          setHomeData((prev) => ({
            ...prev,
            stationBaseStatus: stationBaseStatus,
          }));
        }
      } catch (error) {
        console.error('Failed to load overview data:', error);
      }
    };

    const fetchBatteryData = async () => {
      try {
        const response = await mainPageControllerGetOverviewData({
          stationId: stationId,
          areaId: areaId,
        });
        if (response.success) {
          const data = response.data;
          console.log('fetchBatteryData---', data);
          const stationBatteryData = [
            {
              stationSoc: data?.batteryData?.stationSoc,
              soc: {
                boxName: data?.batteryData?.socExtreme?.boxName,
                max: data?.batteryData?.socExtreme?.max,
                min: data?.batteryData?.socExtreme?.min,
              },
              temperature: {
                boxName: data?.batteryData?.tempExtreme?.boxName,
                min: data?.batteryData?.tempExtreme?.min,
                max: data?.batteryData?.tempExtreme?.max,
              },
              voltageExtreme: {
                boxName: data?.batteryData?.voltageExtreme?.boxName,
                min: data?.batteryData?.voltageExtreme?.min,
                max: data?.batteryData?.voltageExtreme?.max,
              },
              currentExtreme: {
                boxName: data?.batteryData?.currentExtreme?.boxName,
                min: data?.batteryData?.currentExtreme?.min,
                max: data?.batteryData?.currentExtreme?.max,
              },
            },
          ];
          setHomeData((prev) => ({
            ...prev,
            stationBatteryData: stationBatteryData,
          }));
        }
      } catch (error) {
        console.error('Failed to load overview data:', error);
      }
    };

    const fetchMainData = async () => {
      try {
        const response = await mainPageControllerGetOverviewData({
          stationId: stationId,
          areaId: areaId,
        });
        if (response.success) {
          const data = response.data;
          const stationBaseData = data?.baseData;
          const stationMainData = data?.mainData;
          const stationRealtimeData = data?.realtimeData;
          // @ts-ignore
          setHomeData((prev) => ({
            ...prev,
            stationMainData: stationMainData,
            stationBaseData: stationBaseData,
            stationRealtimeData: stationRealtimeData,
          }));
        }
      } catch (error) {
        console.error('Failed to load overview data:', error);
      }
    };
    const fetchEventInfo = async () => {
      try {
        const response = await mainPageControllerGetEventDatas({ type: '2', areaId: areaId });
        const response2 = await mainPageControllerGetEventDatas({ type: '1', areaId: areaId });
        if (response.success && response.data) {
          const data = response.data;
          const stationWarningEvent = data.slice(0, 10).map((item, index) => ({
            eventKey: index + 1,
            eventGrade: item?.state,
            eventStatus: item?.desc,
            eventPloy: item?.location,
          }));
          setHomeData((prev) => ({
            ...prev,
            stationWarningEvent: stationWarningEvent,
          }));
        }
        if (response2.success && response2.data) {
          const data2 = response2.data;
          const stationPolicyEvent = _.slice(data2, 0, 5).map((item, index) => {
            return {
              eventKey: index + 1,
              eventTime: item?.time,
              eventStatus: item?.state,
              eventPloy: item?.desc,
            };
          });
          setHomeData((prev) => ({
            ...prev,
            stationPolicyEvent: stationPolicyEvent,
          }));
        }
      } catch (error) {
        console.error('Failed to load overview data:', error);
      }
    };
    // 工况接口
    const fetchWorkState = async () => {
      try {
        // 清空旧的 stationWorkState 数据
        setHomeData((prev) => ({
          ...prev,
          stationWorkState: undefined, // 或者你可以设置为一个初始状态
        }));
        const response = await mainPageControllerGetWorkState({
          stationId: stationId,
          areaId: areaId,
        });
        const stationWorkState = response.data;
        if (response.success && response.data) {
          setHomeData((prev) => ({
            ...prev,
            stationWorkState: stationWorkState,
          }));
        }
      } catch (error) {
        console.error('Failed to load overview data:', error);
      }
    };
    // 充放电
    const fetchChargeAndDischarge = async () => {
      const response = await mainPageControllerGetChargeAndDischarge({
        stationId: stationId,
        areaId: areaId,
      });
      try {
        if (response.success && response.data) {
          const data = response.data;
          const stationChargeAndDischarge = {
            dimensions: ['day', '充电', '放电'],
            source: [
              { day: data[0].date, Charge: data[0].chargeCount, Discharge: data[0].dischargeCount },
              { day: data[1].date, Charge: data[1].chargeCount, Discharge: data[1].dischargeCount },
              { day: data[2].date, Charge: data[2].chargeCount, Discharge: data[2].dischargeCount },
              { day: data[3].date, Charge: data[3].chargeCount, Discharge: data[3].dischargeCount },
              { day: data[4].date, Charge: data[4].chargeCount, Discharge: data[4].dischargeCount },
              { day: data[5].date, Charge: data[5].chargeCount, Discharge: data[5].dischargeCount },
              { day: data[6].date, Charge: data[6].chargeCount, Discharge: data[6].dischargeCount },
            ],
          };

          stationChargeAndDischarge.source.forEach((item) => {
            item.day = item?.day?.slice(5); // 提取 'MM-DD' 格式
          });
          setHomeData((prev) => ({
            ...prev,
            stationChargeAndDischarge: stationChargeAndDischarge,
          }));
        }
      } catch (error) {
        console.error('Failed to load overview data:', error);
      }
    };

    fetchOverviewData();
    if (!isOldStation) {
      fetchEventInfo();
    }
    if (isPhotovoltaic) {
      fetchPhotovolaticStaticData();
    } else {
      fetchStatisticsData();
    }
    fetchBaseOverview();
    fetchBatteryData();
    fetchMainData();
    fetchWorkState();
    fetchChargeAndDischarge();
    // 设置定时器，每10秒刷新一次电池信息数据
    const intervalId = setInterval(fetchBatteryData, 10000);
    // 设置定时器，每10分钟刷新一次工况数据
    const workStateintervalId = setInterval(fetchWorkState, 6000000);
    // 设置定时器，每1分钟刷新一次事件信息
    const eventintervalId = setInterval(fetchEventInfo, 60000);
    // 设置定时器，每30分钟刷新一次充电信息
    const chargeintervalId = setInterval(fetchChargeAndDischarge, 1800000);
    // 30 秒刷新整站概况数据
    const overviewId = setInterval(fetchOverviewData, 30000);
    // 30秒刷新 光储充运行指标
    const photovolaticId = setInterval(fetchPhotovolaticStaticData, 30000);
    // 30 秒刷新运行指标数据
    const statusOverviewId = setInterval(fetchStatisticsData, 30000);

    // 10 秒刷新功率数据
    const mainOverviewId = setInterval(fetchMainData, 10000);

    // 组件卸载时清除定时器
    return () => {
      clearInterval(intervalId);
      clearInterval(workStateintervalId);
      clearInterval(eventintervalId);
      clearInterval(chargeintervalId);
      clearInterval(overviewId);
      clearInterval(statusOverviewId);
      clearInterval(mainOverviewId);
      clearInterval(photovolaticId);
    };
  }, [stationId, areaId, isPhotovoltaic]);

  return homeData;
};
